<?php
namespace app\controller\admin;

use app\BaseController;
use think\facade\Request;
use app\model\BlindBoxModel;
use app\model\tool\ImageModel;

/**
 * 盲盒后台管理控制器
 * Class BlindBox
 * @package app\controller\admin
 */
class BlindBox extends BaseController
{
    /**
     * 获取盲盒列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_list(Request $request)
    {
        $_GPC = Request::param();
        $filter = [];
        
        if (isset($_GPC['name'])) {
            $filter['name'] = $_GPC['name'];
        }
        
        if (isset($_GPC['status'])) {
            $filter['status'] = $_GPC['status'];
        }
        
        $list = BlindBoxModel::get_list($filter);
        
        // 处理图片
        foreach ($list as &$item) {
            if (!empty($item['image'])) {
                $item['image'] = ImageModel::resize2($item['image'], 100, 100);
            }
            
            // 计算库存百分比
            if ($item['stock'] > 0) {
                $item['stock_percent'] = round(($item['stock'] - $item['sold']) / $item['stock'] * 100, 2);
            } else {
                $item['stock_percent'] = 100;
            }
        }
        
        return json($list);
    }

    /**
     * 获取盲盒详情
     * @return \think\response\Json
     */
    public function info()
    {
        $blind_box_id = $_GET['blind_box_id'];
        
        $res = [
            'status' => 0,
        ];
        
        $info = BlindBoxModel::detail($blind_box_id);
        
        if (empty($info)) {
            $res['status'] = 1;
            $res['description'] = '盲盒不存在';
            return json($res);
        }
        
        // 获取奖品列表
        $prizes = BlindBoxModel::get_prizes($blind_box_id);
        
        // 处理奖品图片
        // foreach ($prizes as &$prize) {
        //     if (!empty($prize['prize_image'])) {
        //         $prize['prize_image'] = ImageModel::resize2($prize['prize_image']);
        //     }
        // }
        
        $info['prizes'] = $prizes;
        
        $res['blind_box'] = $info;
        
        return json($res);
    }

    /**
     * 创建或编辑盲盒
     * @return \think\response\Json
     */
    public function edit()
    {
        $_GPC = Request::param();
        $blind_box_id = $_GPC['blind_box_id'] ?? 0;
        
        $res = [
            'status' => 0,
            'message' => '保存成功'
        ];
        
        try {
            $data = [
                'name' => $_GPC['name'] ?? '',
                'description' => $_GPC['description'] ?? '',
                'image' => $_GPC['image'] ?? '',
                'price' => $_GPC['price'] ?? 0,
                'stock' => $_GPC['stock'] ?? -1,
                'limit_per_user' => $_GPC['limit_per_user'] ?? 0,
                'start_time' => $_GPC['start_time'] ?? '',
                'end_time' => $_GPC['end_time'] ?? '',
                'status' => $_GPC['status'] ?? 1,
                'sort_order' => $_GPC['sort_order'] ?? 0,
            ];
            
            $blind_box_id = BlindBoxModel::edit($blind_box_id, $data);
            
            // 保存奖品配置
            if (isset($_GPC['prizes'])) {
                $prizes = $_GPC['prizes'];
                if (is_string($prizes)) {
                    $prizes = json_decode($prizes, true);
                }
                BlindBoxModel::save_prizes($blind_box_id, $prizes);
            }
            
            $res['blind_box_id'] = $blind_box_id;
            
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '保存失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 逻辑删除盲盒
     * @return \think\response\Json
     */
    public function remove()
    {
        $_GPC = Request::param();
        $ids = $_GPC['ids'];
        
        $res = [
            'status' => 0,
            'message' => '删除成功'
        ];
        
        try {
            $result = BlindBoxModel::remove($ids);
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '删除失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 恢复已删除的盲盒
     * @return \think\response\Json
     */
    public function restore()
    {
        $ids = $_POST['ids'];
        
        $res = [
            'status' => 0,
            'message' => '恢复成功'
        ];
        
        try {
            $result = BlindBoxModel::restore($ids);
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '恢复失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 盲盒上架
     * @return \think\response\Json
     */
    public function onSale()
    {
        $_GPC = Request::param();
        $ids = $_GPC['ids'];
        
        $res = [
            'status' => 0,
            'message' => '上架成功'
        ];
        
        try {
            $result = BlindBoxModel::updateStatus($ids, 1);
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '上架失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 盲盒下架
     * @return \think\response\Json
     */
    public function offSale()
    {
        $_GPC = Request::param();
        $ids = $_GPC['ids'];
        
        $res = [
            'status' => 0,
            'message' => '下架成功'
        ];
        
        try {
            $result = BlindBoxModel::updateStatus($ids, 0);
            $res['affected_rows'] = $result;
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '下架失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 获取抽奖记录列表
     * @return \think\response\Json
     */
    public function get_records()
    {
        $_GPC = Request::param();
        $filter = [];
        
        // 支持通过盲盒ID或盲盒名称筛选
        if (isset($_GPC['blind_box_id'])) {
            $filter['blind_box_id'] = $_GPC['blind_box_id'];
        } else if (isset($_GPC['blind_box_name'])) {
            $filter['blind_box_name'] = $_GPC['blind_box_name'];
        }
        
        if (isset($_GPC['customer_name'])) {
            $filter['customer_name'] = $_GPC['customer_name'];
        }
        
        // 分页参数
        $page = isset($_GPC['page']) ? intval($_GPC['page']) : 1;
        $per_page = isset($_GPC['per_page']) ? intval($_GPC['per_page']) : 15;
        $offset = ($page - 1) * $per_page;
        
        // 获取总记录数
        $total = BlindBoxModel::get_all_records_count($filter);
        
        // 获取分页数据
        $list = BlindBoxModel::get_all_records($filter, $offset, $per_page);
        
        // 处理图片
        foreach ($list as &$item) {
            if (!empty($item['prize_image'])) {
                $item['prize_image'] = ImageModel::resize2($item['prize_image'], 60, 60);
            }
        }
        
        return json([
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'per_page' => $per_page
        ]);
    }

    /**
     * 发放奖品
     * @return \think\response\Json
     */
    public function deliver_prize()
    {
        $_GPC = Request::param();
        $record_id = $_GPC['record_id'];
        $remark = $_GPC['remark'] ?? '';
        
        $res = [
            'status' => 0,
            'message' => '发放成功'
        ];
        
        try {
            BlindBoxModel::deliver_prize($record_id, $remark);
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '发放失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 获取盲盒统计数据
     * @return \think\response\Json
     */
    public function statistics()
    {
        $blind_box_id = $_GET['blind_box_id'] ?? 0;
        
        $res = [
            'status' => 0
        ];
        
        if ($blind_box_id) {
            // 单个盲盒统计
            $blind_box = BlindBoxModel::detail($blind_box_id);
            $prizes = BlindBoxModel::get_prizes($blind_box_id);
            
            $stats = [
                'total_sold' => $blind_box['sold'],
                'total_revenue' => $blind_box['sold'] * $blind_box['price'],
                'prize_stats' => []
            ];
            
            foreach ($prizes as $prize) {
                $drawn_count = $prize['total_stock'] - $prize['remain_stock'];
                if ($prize['total_stock'] == -1) {
                    $drawn_count = 0; // 无限库存时需要从记录表查询
                }
                
                $stats['prize_stats'][] = [
                    'prize_name' => $prize['prize_name'],
                    'prize_level' => $prize['prize_level'],
                    'total_stock' => $prize['total_stock'],
                    'remain_stock' => $prize['remain_stock'],
                    'drawn_count' => $drawn_count,
                    'probability' => $prize['probability']
                ];
            }
            
            $res['statistics'] = $stats;
        }
        
        return json($res);
    }

    /**
     * 获取已购买盲盒订单详情
     * @return \think\response\Json
     */
    public function orderInfo()
    {
        $_GPC = Request::param();
        $order_id = $_GPC['order_id'] ?? 0;
        
        $res = [
            'status' => 0
        ];
        
        if (empty($order_id)) {
            $res['status'] = 1;
            $res['message'] = '请提供订单ID';
            return json($res);
        }
        
        try {
            $order_detail = BlindBoxModel::get_order_detail($order_id);
            
            if (empty($order_detail)) {
                $res['status'] = 1;
                $res['message'] = '订单不存在';
                return json($res);
            }
            
            // 处理图片
            if (!empty($order_detail['blind_box_image'])) {
                $order_detail['blind_box_image'] = ImageModel::resize2($order_detail['blind_box_image'], 200, 200);
            }
            
            if (!empty($order_detail['customer_avatar'])) {
                $order_detail['customer_avatar'] = ImageModel::resize2($order_detail['customer_avatar'], 100, 100);
            }
            
            // 处理抽奖记录中的图片
            if (!empty($order_detail['draw_records'])) {
                foreach ($order_detail['draw_records'] as &$record) {
                    if (!empty($record['prize_image'])) {
                        $record['prize_image'] = ImageModel::resize2($record['prize_image'], 150, 150);
                    }
                }
            }
            
            // 格式化订单状态
            $order_detail['status_text'] = self::getOrderStatusText($order_detail['status']);
            $order_detail['payment_method_text'] = self::getPaymentMethodText($order_detail['payment_method']);
            $order_detail['shipping_method_text'] = $order_detail['shipping_method'] == 'package' ? '快递配送' : '到店自提';
            $order_detail['is_payed_text'] = $order_detail['is_payed'] ? '已支付' : '未支付';
            $order_detail['is_drawn_text'] = $order_detail['is_drawn'] ? '已抽奖' : '未抽奖';
            
            // 计算抽奖延迟时间
            if ($order_detail['draw_time'] && $order_detail['create_time']) {
                $order_detail['draw_delay_seconds'] = strtotime($order_detail['draw_time']) - strtotime($order_detail['create_time']);
                $order_detail['draw_delay_text'] = self::formatDuration($order_detail['draw_delay_seconds']);
            }
            
            $res['order'] = $order_detail;
            
        } catch (\Exception $e) {
            $res['status'] = 1;
            $res['message'] = '获取订单详情失败：' . $e->getMessage();
        }
        
        return json($res);
    }

    /**
     * 获取订单状态文本
     * @param string $status
     * @return string
     */
    private static function getOrderStatusText($status)
    {
        $statusMap = [
            'pending' => '待支付',
            'processing' => '处理中',
            'shipping' => '配送中',
            'completed' => '已完成',
            'canceled' => '已取消'
        ];
        
        return $statusMap[$status] ?? '未知';
    }

    /**
     * 获取支付方式文本
     * @param string $method
     * @return string
     */
    private static function getPaymentMethodText($method)
    {
        $methodMap = [
            'wechat' => '微信支付',
            'alipay' => '支付宝',
            'cash' => '现金支付',
            'balance' => '余额支付'
        ];
        
        return $methodMap[$method] ?? $method;
    }

    /**
     * 格式化时间间隔
     * @param int $seconds
     * @return string
     */
    private static function formatDuration($seconds)
    {
        if ($seconds < 60) {
            return $seconds . '秒';
        } elseif ($seconds < 3600) {
            return floor($seconds / 60) . '分钟';
        } elseif ($seconds < 86400) {
            $hours = floor($seconds / 3600);
            $minutes = floor(($seconds % 3600) / 60);
            return $hours . '小时' . ($minutes > 0 ? $minutes . '分钟' : '');
        } else {
            $days = floor($seconds / 86400);
            $hours = floor(($seconds % 86400) / 3600);
            return $days . '天' . ($hours > 0 ? $hours . '小时' : '');
        }
    }
}
